package com.songlanyun.common.utils.custom;


import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 信号量 工具类
 */
public class SemaphoreUtils {


    /**
     * 设置信号量
     */
    public static boolean setPermits(RSemaphore semaphore, int size) {
        return semaphore.trySetPermits(size);
    }

    /**
     * 获得信号量
     */
    public static boolean getPermits(RSemaphore semaphore, int size) {
        try {
            semaphore.acquire(size);
            return true;//获取信号量成功
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;//获取信号量失败
        }
    }

    /**
     * 释放信号量
     */
    public static void release(RSemaphore semaphore, int size) {
        semaphore.release(size);//释放信号量
    }

    /**
     * 信号量的permits数
     * 获取当前信号量的剩余数量
     */
    public static int permitsNum(RSemaphore semaphore) {
        return semaphore.availablePermits();
    }

    /**
     * 清空permits
     *
     */
    public static int drainPermits(RSemaphore semaphore) {
        return semaphore.drainPermits();
    }




}
